﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint;
using System.Security.Permissions;
using Slam.SharePoint;
using SlamCms.SharePoint.Tagging.Services;
using SlamCms.SharePoint.FieldTypes;
using SlamCms.SharePoint.Core;
using SlamCms.Data;
using SlamCms.Common;
using Slam.FieldTypes;

namespace SlamCms.SharePoint.Tagging.FieldTypes
{
	public partial class FeatureOnTagFieldControl : SlamFieldControl
	{	
		protected HtmlGenericControl editFeaturedTagsArea;
		protected HtmlGenericControl tagListing;
		protected HtmlGenericControl editModalLink;
		protected HtmlGenericControl tagModal;
		protected Literal ltNoTags;

		protected Button btnCancel;
		protected Button btnOk;

		protected HtmlAnchor editTags;
		protected Repeater rptFeaturableCategories;

		protected HtmlGenericControl errors;
		protected HiddenField hdnValueField;

		protected HtmlGenericControl displayTagsArea;
		protected Literal ltDisplayTags;

		private ContentItem _contentItem;
		private ContentItem ContentItem
		{
			get
			{
				if (_contentItem == null)
					_contentItem = SlamCmsContext.Data.CreateQuery().FilterStatus(FilterStatus.None).FilterZone(Zone.ZoneId).Filter("ContentItem.ContentItemID = '{0}'", SlamId).IncludeTags().Cache(QueryCacheBehavior.NoCache).Get().FirstOrDefault();
				return _contentItem;
			}
		}

		protected override string DefaultTemplateName
		{
			get { return "SlamCMSFeatureOnTagFieldControlTemplate"; }
		}

		public override string DisplayTemplateName
		{
			get
			{
				return "SlamCMSFeatureOnTagFieldControlDisplayTemplate";
			}
			set
			{
				base.DisplayTemplateName = value;
			}
		}

		public string DisplayNameColumnNameService
		{
			get;
			set;
		}

		private FeatureOnTagFieldServices _fieldServices;
		private FeatureOnTagFieldServices FieldServices
		{
			get
			{
				if (_fieldServices == null)
				{
					_fieldServices = new FeatureOnTagFieldServices();
				}
				return _fieldServices;
			}
		}

		private string SlamContentType
		{
			get;
			set;
		}

		private string SlamId
		{
			get;
			set;
		}

		private TagTree _tagTree;
		private TagTree UserFeaturableTagTree
		{
			get
			{
				if (_tagTree == null)
				{

					_tagTree = SlamCmsContext.Data.GetTagTree(Zone.ZoneId).
						Localize(SlamCmsContext.User.Language).
						FilterTagScope(SlamContentType);

					string[] tagIdentifiers = _tagTree.FindNodes(n => !String.IsNullOrEmpty(n.Identifier)).Select(t => t.Identifier).ToArray();
					if (SlamCmsContext.User.Groups != null && SlamCmsContext.User.Groups.Any(g => g.Name.Equals(Constants.GroupNames.GlobalFeatureLocationOwner)))
					{
						tagIdentifiers = _tagTree.FindNodes(n => !String.IsNullOrEmpty(n.Identifier)).Select(t => t.Identifier).ToArray();
						_tagTree = _tagTree.SetRestrictAccessForTags(tagIdentifiers, false);
					}
					else 
					{
						_tagTree = _tagTree.SetRestrictAccessForTags(tagIdentifiers, true);
						if (SlamCmsContext.User.OwnedTags != null)
						{
							tagIdentifiers = SlamCmsContext.User.OwnedTags.Select(t => t.Identifier).ToArray();
							_tagTree = _tagTree.SetRestrictAccessForTags(tagIdentifiers, false);
						}
					}
				}
				return _tagTree;
			}
		}

		private IEnumerable<FeatureLocation> _userFeatureLocations;
		private IEnumerable<FeatureLocation> UserFeatureLocations
		{
			get
			{
				if (_userFeatureLocations == null)
				{
					if (SlamCmsContext.User.Groups != null && SlamCmsContext.User.Groups.Any(g => g.Name.Equals(Constants.GroupNames.GlobalFeatureLocationOwner)))
					{
						_userFeatureLocations = SlamCmsContext.Data.FeatureLocations;
					}
					else if (SlamCmsContext.User.OwnedFeatureLocations != null)
					{
						_userFeatureLocations = SlamCmsContext.User.OwnedFeatureLocations;
					}

					if (_userFeatureLocations != null)
					{
						_userFeatureLocations = _userFeatureLocations.Where(f => f.Scopes == null || (f.Scopes != null && (f.Scopes.Count == 0 || f.Scopes.Any(s => s.Title == SlamContentType))));
					}
					else
					{
						_userFeatureLocations = new List<FeatureLocation>();
					}
				}

				return _userFeatureLocations;
			}
		}

		private Zone _zone;
		private Zone Zone
		{
			get
			{
				if (_zone == null)
				{
					_zone = SlamCmsContext.Data.Zones.Where(z => z.Sites.Any(s => s.SiteId == Web.ID)).FirstOrDefault();
				}

				if (_zone == null)
				{
					_zone = SlamCmsContext.Data.Zones.FirstOrDefault();
				}
				return _zone;
			}
		}

		public override object Value
		{
			get
			{
				EnsureChildControls();

				List<FeatureOnTagValue> currentTags = FeatureOnTagFieldServices.ParseFeatureOnTagValue(hdnValueField.Value);
				List<FeatureOnTagValue> selectedTags = new List<FeatureOnTagValue>();

				foreach (RepeaterItem item in rptFeaturableCategories.Items)
				{
					foreach (RepeaterItem innerItem in ((Repeater)item.FindControl("rptFeaturableTags")).Items)
					{
						CheckBox chkTagFeatured = innerItem.FindControl("chkTagFeatured") as CheckBox;
						DropDownList ddlFeatureLevels = innerItem.FindControl("ddlFeatureLevels") as DropDownList;
						HiddenField hdnTagId = innerItem.FindControl("hdnTagId") as HiddenField;
						HiddenField hdnValueType = innerItem.FindControl("hdnValueType") as HiddenField;
						if (!String.IsNullOrEmpty(hdnTagId.Value) && hdnTagId.Value != "0")
						{
							if (chkTagFeatured.Checked)
							{
								FeatureOnTagValue tagValue = new FeatureOnTagValue();
								tagValue.Id = hdnTagId.Value;

								tagValue.Title = chkTagFeatured.Text;
								tagValue.FeatureLevel = ddlFeatureLevels.SelectedValue;
								tagValue.Type = (FeatureType)Enum.Parse(typeof(FeatureType), hdnValueType.Value);
								selectedTags.Add(tagValue);
							}

							FeatureOnTagValue currentTag = currentTags.Find(x => x.Id == hdnTagId.Value);
							currentTags.Remove(currentTag);
						}
					}
				}

				currentTags.AddRange(selectedTags);
				return FeatureOnTagFieldServices.GetFeatureOnTagValue(currentTags);
			}
			set
			{
				EnsureChildControls();
				SetFieldControlValue(value);
			}
		}

		[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
		public override void Validate()
		{
			string currentValue = (string)Value;
			SetFieldControlValue(currentValue);
			tagListing.InnerHtml = FormatValueForDisplay(hdnValueField.Value);

			if (((base.ControlMode != SPControlMode.Display) && base.IsValid && base.Field.Required) && (currentValue != null))
			{
				base.Validate();
				errors.Visible = false;
				if (String.IsNullOrEmpty(currentValue))
				{
					base.IsValid = false;
					base.ErrorMessage = SPResource.GetString("MissingRequiredField", new object[0]);
					//errors.InnerHtml = SPResource.GetString("MissingRequiredField", new object[0]);
					//errors.Visible = true;
				}
			}
		}

		private void SetFieldControlValue(object value)
		{
			if (value != null && (String.IsNullOrEmpty(hdnValueField.Value) || hdnValueField.Value != value.ToString()))
			{
				var parsedValues = FeatureOnTagFieldServices.ParseFeatureOnTagValue(Convert.ToString(value));
				List<FeatureOnTagValue> verifiedValues = new List<FeatureOnTagValue>();
				foreach (var tagTreeNode in SlamCmsContext.Data.GetTagTree(Zone.ZoneId).Localize(SlamCmsContext.User.Language).FilterTagScope(SlamContentType).FindNodes(n => n.Type == TagTreeNodeType.Tag))
				{
					var matchedValue = parsedValues.Where(v => v.Type == FeatureType.Tag && v.Id == tagTreeNode.Tag.TagId).FirstOrDefault();
					if (matchedValue != null)
						verifiedValues.Add(matchedValue);
				}

				foreach (var featureLocation in SlamCmsContext.Data.FeatureLocations)
				{
					var matchedValue = parsedValues.Where(v => v.Type == FeatureType.FeatureLocation && v.Id == featureLocation.FeatureLocationId).FirstOrDefault();
					if (matchedValue != null)
						verifiedValues.Add(matchedValue);
				}
				hdnValueField.Value = FeatureOnTagFieldServices.GetFeatureOnTagValue(verifiedValues);
			}
		}

		private string FormatValueForDisplay(string value)
		{
			string outputValue = "";
			string featureLevelName = "";
			foreach (FeatureOnTagValue tag in FeatureOnTagFieldServices.ParseFeatureOnTagValue(value))
			{
				switch (tag.FeatureLevel)
				{
					case "1":
						featureLevelName = "High";
						break;
					case "0":
						featureLevelName = "Med";
						break;
					case "-1":
						featureLevelName = "Low";
						break;
					default:
						featureLevelName = "Med";
						break;
				}
				outputValue += tag.Title + " (" + featureLevelName + "), ";
			}
			if (outputValue.Length > 0)
			{
				outputValue = outputValue.Remove(outputValue.Length - 2);
			}
			return outputValue;
		}

		private void LoadSlamPropertiesForItem()
		{
			SlamCmsContext.SharePoint.WithElevatedPrivileges().
				SiteCollection(Web.Site.ID).
				Site(Web.ID).
				List(ListId).
				NewItem(elevatedListItem =>
				{
					elevatedListItem["ContentTypeId"] = Item["ContentTypeId"];
					elevatedListItem["SLAM ID"] = Item["SLAM ID"];

					if (Page.Request.QueryString["ContentTypeId"] != Convert.ToString(elevatedListItem["ContentTypeId"]))
					{
						elevatedListItem["ContentTypeId"] = Page.Request.QueryString["ContentTypeId"];
					}

					SlamContentType = FieldServices.GetScopeForListItem(elevatedListItem);
					if (elevatedListItem["SLAM ID"] != null)
						SlamId = Convert.ToString(elevatedListItem["SLAM ID"]);
				});
		}

		protected void FindControls()
		{
			editFeaturedTagsArea = (HtmlGenericControl)TemplateContainer.FindControl("editFeaturedTagsArea");
			tagListing = (HtmlGenericControl)TemplateContainer.FindControl("tagListing");
			editModalLink = (HtmlGenericControl)TemplateContainer.FindControl("editModalLink");
			tagModal = (HtmlGenericControl)TemplateContainer.FindControl("tagModal");
			btnCancel = (Button)TemplateContainer.FindControl("btnCancel");
			btnOk = (Button)TemplateContainer.FindControl("btnOk");
			rptFeaturableCategories = (Repeater)TemplateContainer.FindControl("rptFeaturableCategories");
			errors = (HtmlGenericControl)TemplateContainer.FindControl("errors");
			hdnValueField = (HiddenField)TemplateContainer.FindControl("hdnValueField");
			editTags = (HtmlAnchor)TemplateContainer.FindControl("editTags");
			ltNoTags = (Literal)TemplateContainer.FindControl("ltNoTags");
		}

		private void AddCssIncludes()
		{
			bool addCssReference = true;
			string cssInclude = String.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" media=\"all\" />", ResolveUrl("~/_layouts/1033/STYLES/SlamCms.Tagging.css"));

			foreach (Control control in Page.Header.Controls)
			{
				if (control is LiteralControl && ((LiteralControl)control).Text == cssInclude)
				{
					addCssReference = false;
				}
			}
			if (addCssReference)
			{
				Page.Header.Controls.Add(new LiteralControl(cssInclude));
			}
		}

		protected override void CreateChildControls()
		{	
			if (Field != null)
			{
				base.CreateChildControls();

				AddCssIncludes();
				LoadSlamPropertiesForItem();

				if (ControlMode == SPControlMode.Display)
				{
					displayTagsArea = (HtmlGenericControl)TemplateContainer.FindControl("displayTagsArea");

					ltDisplayTags = (Literal)TemplateContainer.FindControl("ltDisplayTags");
					if (ItemFieldValue != null)
					{
						ltDisplayTags.Text = FormatValueForDisplay(ItemFieldValue.ToString());
					}
				}
				else if (ControlMode == SPControlMode.Edit || ControlMode == SPControlMode.New)
				{
					if (!base.IsFieldValueCached)
					{
						FindControls();

						if (!this.Page.IsPostBack && ControlMode == SPControlMode.Edit && ItemFieldValue != null)
						{
							SetFieldControlValue(ItemFieldValue);
						}

						rptFeaturableCategories.ItemDataBound += new RepeaterItemEventHandler(rptFeaturableCategories_ItemDataBound);

						var featurableTagCategories = SlamCmsContext.Data.TagCategories.Where(tc => tc.Featurable != "Never").ToList();
						TagCategory featureLocationsCategory = new TagCategory();
						featureLocationsCategory.TagCategoryId = "0";
						featureLocationsCategory.Title = "Feature Locations";
						featureLocationsCategory.Featurable = "Always";
						featurableTagCategories.Insert(0, featureLocationsCategory);
						if (!Page.IsPostBack)
						{
							rptFeaturableCategories.DataSource = featurableTagCategories;
							rptFeaturableCategories.DataBind();
						}

						ltNoTags.Visible = featurableTagCategories.Count == 0;
						tagListing.InnerHtml = FormatValueForDisplay(hdnValueField.Value);

						if (String.IsNullOrEmpty(tagListing.InnerHtml))
						{
							tagListing.InnerHtml = "&nbsp;&nbsp;&nbsp;";
						}

						Page.ClientScript.RegisterClientScriptInclude("jquery", ResolveUrl("~/_layouts/inc/jquery-1.6.2.min.js"));
						Page.ClientScript.RegisterClientScriptInclude("jquery.blockUI", ResolveUrl("~/_layouts/inc/jquery.blockUI.js"));

						string setupModalString =
						@"
							var " + tagModal.ClientID.TrimStart('#') + @"Selections = '';
							var " + tagModal.ClientID.TrimStart('#') + @"Levels = '';
							function updateFeatureOnTagOptions(autoUpdateDisplay)
							{
								$('.featureditemhandle').next().hide(); 
								$('.featureditemhandle').parents('.tag-feature-modal-list').hide(); 
								$('.featureditemhandle').parents('.tag-feature-modal-list').prev().hide(); 
								$('.uneditablefeatureditemhandle').next().hide(); 
								$('.uneditablefeatureditemhandle').parents('.tag-feature-modal-list').hide(); 
								$('.uneditablefeatureditemhandle').parents('.tag-feature-modal-list').prev().hide(); 
								";
						foreach (var category in featurableTagCategories)
						{
							if (category.Featurable.Equals("Conditional", StringComparison.OrdinalIgnoreCase))
							{
								string categoryTitle = Regex.Replace(category.Title, "[\\W\\s]", "");
								setupModalString += @" 
									if($('#TagFieldCategory" + category.TagCategoryId + @"') != null)
									{
										var " + categoryTitle + @"Value = $('#TagFieldCategory" + category.TagCategoryId + @"').next().val();                                 
										if(" + categoryTitle + @"Value != null && " + categoryTitle + @"Value != '')
										{
											var " + categoryTitle + @"Values = " + categoryTitle + @"Value.split(',');
											for(k = 0; k < " + categoryTitle + @"Values.length; k++) 
											{

												$('#FeatureTag" + categoryTitle + "' + " + categoryTitle + @"Values[k]).next().show();
												$('#FeatureTag" + categoryTitle + "' + " + categoryTitle + @"Values[k]).parents('.tag-feature-modal-list').show();
												$('#FeatureTag" + categoryTitle + "' + " + categoryTitle + @"Values[k]).parents('.tag-feature-modal-list').prev().show();
											}
										}
									}
								";
							}
							else if (category.Featurable.Equals("Always", StringComparison.OrdinalIgnoreCase))
							{
								string categoryTitle = Regex.Replace(category.Title, "[\\W\\s]", "");
								setupModalString += @" 
									$('.alwaysfeatureditemhandle').parents('.tag-feature-modal-list').prev(""div:contains('" + category.Title + @"')"").next().show();
								";
							}
						}

						setupModalString +=
								@"
								var boxesToHide = $('.featureditemhandle').next().filter(function() { return $(this).css(""display"") == ""none"" }).find(':checkbox');
								var levelsToHide = $('.featureditemhandle').next().filter(function() { return $(this).css(""display"") == ""none"" }).find('select');
								for(var c = 0; c < boxesToHide.size(); c++)
								{
									if(boxesToHide[c].checked)
									{   
										levelsToHide[c].disabled = true;
									}

									boxesToHide[c].checked = false;
								}

								var checkBoxes = $('#featurableTags :checkbox');
								var featureLevels = $('#featurableTags select');
								for(var c = 0; c < checkBoxes.size(); c++)
								{
									" + tagModal.ClientID.TrimStart('#') + @"Selections += checkBoxes[c].checked + ',';
									" + tagModal.ClientID.TrimStart('#') + @"Levels += featureLevels[c].selectedIndex + ',';
									
								}
								if(" + tagModal.ClientID.TrimStart('#') + @"Selections.length > 0)
								{
									" + tagModal.ClientID.TrimStart('#') + @"Selections = " + tagModal.ClientID.TrimStart('#') + @"Selections.substr(0, " + tagModal.ClientID.TrimStart('#') + @"Selections.length - 1);
									" + tagModal.ClientID.TrimStart('#') + @"Levels = " + tagModal.ClientID.TrimStart('#') + @"Levels.substr(0, " + tagModal.ClientID.TrimStart('#') + @"Levels.length - 1);
								} 

								if(autoUpdateDisplay)
								{
									$('#" + btnOk.ClientID + @"').click();
								}
							}

							$(document).ready(function() {
								$.blockUI.defaults.css = {};
								$.blockUI.defaults.fadeIn = 0;
								$.blockUI.defaults.fadeOut = 0;
												
												
								$('#" + editTags.ClientID + @"').click(function() {
									updateFeatureOnTagOptions(false);
									$.blockUI({ message: $('#" + tagModal.ClientID + @"') });
								});
												
								$('#featurableTags :checkbox').click(function()
								{   
									var selectElement = $(this).parents('div:first').parent().find('select');
									if(this.checked)
									{   
										selectElement.removeAttr('disabled');
									}
									else
									{
										selectElement.attr('disabled', true);
									}
								});            
							});
						";

						Page.ClientScript.RegisterStartupScript(GetType(), "setupModal" + tagModal.ClientID, setupModalString, true);

						btnOk.OnClientClick = @"$.unblockUI({ onUnblock:
							function()
							{
								var checkBoxes = $('#featurableTags :checkbox');
								var featureLevels = $('#featurableTags select');
								var names = $('#featurableTags label');
								var selectedTags = '';
								for(var c = 0; c < checkBoxes.length; c++)
								{
									if(checkBoxes[c].checked)
									{   
										selectedTags = selectedTags + names[c].innerHTML + ' (' + featureLevels[c].options[featureLevels[c].selectedIndex].text + '), ';
									}
								}
								if(selectedTags.length > 0)
								{   
									selectedTags = selectedTags.substr(0, selectedTags.length - 2);
								}
								else
								{
									selectedTags = '&nbsp;&nbsp;&nbsp;';
								}
								$('#" + tagListing.ClientID + @"').html(selectedTags);
								" + tagModal.ClientID.TrimStart('#') + @"Selections = '';
								" + tagModal.ClientID.TrimStart('#') + @"Levels = '';
							}
						}); return false";

						btnOk.UseSubmitBehavior = false;
						btnOk.CausesValidation = false;

						btnCancel.OnClientClick = @"$.unblockUI({ onUnblock:
							function()
							{
								var checkBoxes = $('#featurableTags :checkbox');
								var featureLevels = $('#featurableTags select');
								var selections = " + tagModal.ClientID.TrimStart('#') + @"Selections.split(',');
								var levels = " + tagModal.ClientID.TrimStart('#') + @"Levels.split(',');
								for(var c = 0; c < checkBoxes.length; c++)
								{
									checkBoxes[c].checked = (selections[c] == 'true');
									featureLevels[c].selectedIndex = levels[c];
								}
								" + tagModal.ClientID.TrimStart('#') + @" = '';
							}
						}); return false";

						btnCancel.UseSubmitBehavior = false;
						btnCancel.CausesValidation = false;
					}
				}
			}
		}

		protected void rptFeaturableCategories_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				TagCategory category = (TagCategory)e.Item.DataItem;

				Repeater rptFeaturableTags = e.Item.FindControl("rptFeaturableTags") as Repeater;
				Literal ltCategoryTitle = e.Item.FindControl("ltCategoryTitle") as Literal;

				rptFeaturableTags.ItemDataBound += new RepeaterItemEventHandler(rptFeaturableTags_ItemDataBound);

				List<FeatureTagItem> featureTags = new List<FeatureTagItem>();

				if (category.Title.Equals("Feature Locations"))
				{
					featureTags = UserFeatureLocations.Select(f => new FeatureTagItem()
					{
						Id = f.FeatureLocationId,
						Title = f.Title,
						Type = FeatureType.FeatureLocation,
						Editable = true,
						FeatureLevel = 0,
						ListRelativeId = 0
					}).ToList();
				}
				else
				{
					featureTags = UserFeaturableTagTree.DeepClone<TagTree>().FilterTagCategories(new string[] { category.TagCategoryId }).
						FindNodes(n => n.Type == TagTreeNodeType.Tag && !n.Tag.RestrictAccess).Select(t => new FeatureTagItem()
						{
							Id = t.Tag.TagId,
							Title = GetTagTreeNodeTitleWithParentage(t, (String.IsNullOrEmpty(t.Text) ? t.Identifier : t.Text)),
							Type = FeatureType.Tag,
							Editable = true,
							FeatureLevel = 0,
							ListRelativeId = t.Tag.ListRelativeId
						}).ToList();
				}

				if (category.Featurable.Equals("Always", StringComparison.OrdinalIgnoreCase))
				{
					ltCategoryTitle.Text = category.Title;
				}
				else
				{
					ltCategoryTitle.Text = "Feature on " + category.Title;
				}

				if (featureTags.Count > 0)
				{
					rptFeaturableTags.DataSource = featureTags;
					rptFeaturableTags.DataBind();
				}
				else
				{
					e.Item.Visible = false;
				}
			}

		}

		private string GetTagTreeNodeTitleWithParentage(SlamCms.Data.TagTreeNode currentNode, string title)
		{
			if (currentNode.Parent.Type == TagTreeNodeType.Tag)
			{
				title = GetTagTreeNodeTitleWithParentage(currentNode.Parent, title) + " > " + (String.IsNullOrEmpty(currentNode.Text) ? currentNode.Identifier : currentNode.Text);
			}
			else
			{
				title = String.IsNullOrEmpty(currentNode.Text) ? currentNode.Identifier : (String.IsNullOrEmpty(currentNode.Text) ? currentNode.Identifier : currentNode.Text);
			}
			return title;
		}

		protected void rptFeaturableTags_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
			{
				FeatureTagItem tag = (FeatureTagItem)e.Item.DataItem;
				TagCategory category = (TagCategory)((RepeaterItem)e.Item.Parent.Parent).DataItem;

				CheckBox chkTagFeatured = e.Item.FindControl("chkTagFeatured") as CheckBox;
				HiddenField hdnTagId = e.Item.FindControl("hdnTagId") as HiddenField;
				HiddenField hdnValueType = e.Item.FindControl("hdnValueType") as HiddenField;
				DropDownList ddlFeatureLevels = e.Item.FindControl("ddlFeatureLevels") as DropDownList;
				HtmlGenericControl featurableTagsItem = e.Item.FindControl("featurableTagsItem") as HtmlGenericControl;
				Literal ltItemHandle = e.Item.FindControl("ltItemHandle") as Literal;

				if (category.Featurable.Equals("Conditional", StringComparison.OrdinalIgnoreCase) && tag.Editable)
				{
					ltItemHandle.Text = "<span id=\"FeatureTag" + Regex.Replace(category.Title, "[\\W\\s]", "") + tag.ListRelativeId + "\" class=\"featureditemhandle\"></span>";
				}
				else if (category.Featurable.Equals("Always", StringComparison.OrdinalIgnoreCase) && tag.Editable)
				{
					ltItemHandle.Text = "<span id=\"FeatureTag" + Regex.Replace(category.Title, "[\\W\\s]", "") + tag.ListRelativeId + "\" class=\"alwaysfeatureditemhandle\"></span>";
				}
				else if (!tag.Editable)
				{
					ltItemHandle.Text = "<span id=\"" + Regex.Replace(category.Title, "[\\W\\s]", "") + tag.ListRelativeId + "\" class=\"uneditablefeatureditemhandle\"></span>";
				}
				chkTagFeatured.Text = tag.Title;
				hdnTagId.Value = tag.Id;
				hdnValueType.Value = tag.Type.ToString();

				List<FeatureOnTagValue> currentFeatureTags = FeatureOnTagFieldServices.ParseFeatureOnTagValue(hdnValueField.Value);
				var currentFeatureTag = currentFeatureTags.Where(c => c.Id == tag.Id).FirstOrDefault();
				if (currentFeatureTag != null)
				{
					chkTagFeatured.Checked = true;
					System.Web.UI.WebControls.ListItem featureLevelItem = ddlFeatureLevels.Items.FindByValue(currentFeatureTag.FeatureLevel.ToString());
					if (featureLevelItem != null)
					{
						featureLevelItem.Selected = true;
					}
				}
				else
				{
					ddlFeatureLevels.Enabled = false;
				}
			}
		}
	}

}